<?php
/**
 * 后台通用删除
 */

namespace backend\actions;


use backend\component\BaseAction;
use backend\component\ResultFormat;

class DeleteAction extends BaseAction
{

    /**
     * 是否物理删除 如值为false 需要提供字段及假删除的值
     * @var bool
     */
    public $is_physics = true;
    /**
     * 假删除时需要提供此值,设置默认
     * @var array ["status"=> -1]
     */
    public $fieldAndValue = ["status"=>-1];

    /**
     * 执行删除操作
     * @param $id  数据主健id
     */
    public function run($id) {
        if (!$id){
            return ResultFormat::error("删除失败,缺少参数!");
        }
        if ($this->is_physics) {
            return $this->physicsDelete($id);
        } else {
            return $this->logicDelete($id);
        }
    }

    /**
     * 物理删除
     */
    private function physicsDelete($id) {
        $model = $this->modelObj->findOne($id);
        if (!$model) {
            return ResultFormat::error("删除失败,数据不存在");
        }
        if (!$model->delete()) {
            return ResultFormat::error($model->getErrorsToString());
        }
        return ResultFormat::success($this->successMsg);
    }

    /**
     * 逻辑删除
     */
    private function logicDelete($id) {
        $model = $this->modelObj->findOne($id);
        if (!$model) {
            return ResultFormat::error("删除失败,数据不存在");
        }
        if (!$this->fieldAndValue || !is_array($this->fieldAndValue)){
            return ResultFormat::error("删除失败,未设置删除字段");
        }
        if (!$model->updateAttributes($this->fieldAndValue)) {
            return ResultFormat::error("删除失败,原因：".$model->getErrorsToString());
        }
        return ResultFormat::success($this->successMsg);
    }
}